package qwen3

import (
	"context"
	"fmt"
	"gitee.com/mcp-office/agent/llm"
	"io"
	"net/http"
)

const (
	QWenPlusModel = "qwen-plus"
)

type QWenProvider struct {
	llm.Provider
}

// ChatCompletion 主响应结构
type ChatCompletion struct {
	Choices           []Choice    `json:"choices"`
	Object            string      `json:"object"`
	Usage             Usage       `json:"usage"`
	Created           int64       `json:"created"`
	SystemFingerprint interface{} `json:"system_fingerprint"`
	Model             string      `json:"model"`
	ID                string      `json:"id"`
}

// Choice 消息选项结构
type Choice struct {
	Message      llm.ChatCompletionMessage `json:"message"`
	FinishReason string                    `json:"finish_reason"`
	Index        int                       `json:"index"`
}

// Usage 用量统计结构
type Usage struct {
	PromptTokens        int                `json:"prompt_tokens"`
	CompletionTokens    int                `json:"completion_tokens"`
	TotalTokens         int                `json:"total_tokens"`
	PromptTokensDetails PromptTokensDetail `json:"prompt_tokens_details"`
}

// PromptTokensDetail 令牌详情结构
type PromptTokensDetail struct {
	CachedTokens int `json:"cached_tokens"`
}

// NewQWenProvider 创建一个新的实例
// sk-4932e3b6efb64fbcbbe53c0445b05713
func NewQWenProvider(apiKey string) *QWenProvider {
	var qwen QWenProvider
	qwen.BaseUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1"
	qwen.ApiKey = apiKey
	return &qwen
}

func (p *QWenProvider) ChatCompletion(ctx context.Context, req llm.ChatCompletionRequest) (string, error) {
	request, err := llm.NewRequestBuilder(p.ApiKey).
		SetMethod(http.MethodPost).
		SetBaseUrl(p.BaseUrl).
		SetPath("/chat/completions").
		SetBody(req).
		Build(ctx)
	if err != nil {
		return "", err
	}
	resp, err := http.DefaultClient.Do(request)
	if err != nil || resp.StatusCode != http.StatusOK {
		return "", err
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("读取响应体失败: %v", err)
	}
	//var result ChatCompletion
	//err = json.Unmarshal(body, &result)
	//if err != nil {
	//	return "", fmt.Errorf("反序列化失败: %v", err)
	//}
	return string(body), nil
}
